<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- Card卡片视图 -->
    <el-card>
      <!-- 搜索输入框与添加用户区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索与添加区域 -->
          <el-input placeholder="请输入内容"
                    class="input_search"
                    v-model="userInfo.query"
                    clearable
                    @clear="getUserList()">
            <el-button slot="append"
                       icon="el-icon-search"
                       @click="getUserList()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <!-- 添加用户按钮 -->
          <el-button type="primary"
                     @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区 -->
      <el-table :data="userlist"
                border
                stripe
                style="width: 100%">
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username"
                         label="姓名"></el-table-column>
        <el-table-column prop="email"
                         label="邮箱"></el-table-column>
        <el-table-column prop="mobile"
                         label="电话"></el-table-column>
        <el-table-column prop="role_name"
                         label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- scope.row ---》拿到每行的数据 -->
            <!-- {{ scope.row.mg_state }} -->
            <el-switch v-model="scope.row.mg_state"
                       active-text="开"
                       inactive-text="关"
                       @change="userStateChange(scope.row)">
              <!-- @change="switchChange(scope.row)"  --》监控开关的改变 -->
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip class="item"
                        effect="dark"
                        content="编辑角色"
                        placement="top"
                        :enterable="false">
              <el-button type="primary"
                         icon="el-icon-edit"
                         size="mini"
                         @click="showEditDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip class="item"
                        effect="dark"
                        content="删除角色"
                        placement="top"
                        :enterable="false">
              <el-button type="danger"
                         icon="el-icon-delete"
                         size="mini"
                         @click="deleteUserById(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip class="item"
                        effect="dark"
                        content="修改角色"
                        placement="top"
                        :enterable="false">
              <el-button type="warning"
                         icon="el-icon-setting"
                         size="mini"
                         @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="userInfo.pagenum"
                     :page-sizes="[1, 2, 5, 8, 10]"
                     :page-size="userInfo.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </el-card>

    <!-- 增加用户对话框 -->
    <el-dialog title="添加用户"
               :visible.sync="addDialogVisible"
               width="50%"
               @close="addDialogClosed()">
      <!-- 内容主体区 -->
      <el-form :model="addForm"
               :rules="addFormRules"
               ref="addFormRef"
               label-width="70px">
        <el-form-item label="用户名"
                      prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码"
                      prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号"
                      prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区 -->
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addUser()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息对话框 -->
    <el-dialog title="修改用户信息"
               :visible.sync="editDialogVisible"
               width="50%"
               @closed="editDialogClosed">
      <!-- 修改用户信息主要区域 -->
      <el-form :model="editForm"
               :rules="editFormRules"
               ref="editFormRef"
               label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username"
                    disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱"
                      prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号"
                      prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="editUserInfo()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog title="分配角色"
               :visible.sync="setRoleDialogVisible"
               width="50%"
               @close="setRoleDialogClosed()">
      <el-input v-model="user.username"
                :disabled="true"
                prefix-icon="iconfont icon-zhanghao">
      </el-input>
      <el-input v-model="user.role_name"
                :disabled="true"
                prefix-icon="iconfont icon-quanxian">
      </el-input>

      <!-- 分配角色列表 -->
      <el-select v-model="selectedRoleId"
                 placeholder="分配新角色">
        <el-option v-for="item in roleList"
                   :key="item.id"
                   :label="item.roleName"
                   :value="item.id">
        </el-option>
      </el-select>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="saveRoleInfo()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 自定义校验规则，分别校验邮箱和手机号
    var checkEmail = (rules, value, cb) => {
      const regEmail = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/;
      if (regEmail.test(value)) {
        return cb(); //校验通过
      }
      // 不通过的时候向cb函数中传入一个error对象
      cb(new Error("请输入合法的邮箱"));
    };
    var checkMobile = (rules, value, cb) => {
      const regMobile = /1((((3[0-3,5-9])|(4[5,7,9])|(5[0-3,5-9])|(66)|(7[1-3,5-8])|(8[0-9])|(9[1,8,9]))[0-9]{8})|((34)[0-8]\d{7}))/;
      if (regMobile.test(value)) {
        return cb();
      }
      // 不通过的时候向cb函数中传入一个error对象
      cb(new Error("请输入有效的手机号"));
    };

    return {
      // 获取用户列表的参数对象
      userInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2
      },
      userlist: [], //数据总数据列表
      user: {}, // 需要被分配权限的用户
      roleList: {}, //所有角色数据
      selectedRoleId: {
        //保存的角色id值
      },
      total: 0, //总数据条数
      addDialogVisible: false,
      editDialogVisible: false,
      //添加用户表单数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 修改用户表单数据
      editForm: {},
      //添加表单验证的规则对象
      addFormRules: {
        username: [
          { required: true, message: "请输入用户账号", tigger: "blur" },
          { min: 3, max: 10, message: "用户名的长度在3~10之间", tigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", tigger: "blur" },
          { min: 6, max: 15, message: "用户名的长度在3~10之间", tigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", tigger: "blur" },
          { validator: checkEmail, tigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", tigger: "blur" },
          { validator: checkMobile, tigger: "blur" }
        ]
      },
      // 修改用户信息表单验证
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱", tigger: "blur" },
          { validator: checkEmail, tigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", tigger: "blur" },
          { validator: checkMobile, tigger: "blur" }
        ]
      },
      setRoleDialogVisible: false
    };
  },
  methods: {
    // 获取用户列表
    async getUserList () {
      const { data: userlists } = await this.$ajax.get("/users", {
        params: this.userInfo
      });

      if (userlists.meta.status !== 200) {
        return this.$message.error("获取用户列表失败");
      }
      this.userlist = userlists.data.users;
      this.total = userlists.data.total;
    },
    // 改变用户状态
    userStateChange (userRow) {
      this.$ajax
        .put(`users/${userRow.id}/state/${userRow.mg_state}`)
        .then(res => {
          if (res.data.meta.status !== 200) {
            return this.$message.error("更新失败");
          }
          return this.$message.success("更新成功");
        })
        .catch(err => {
          console.log(err);
          return this.$message.success("更新出错");
        });
    },
    // 每页显示条数改变的时候触发的函数
    handleSizeChange (newSize) {
      this.userInfo.pagesize = newSize;
      this.getUserList();
    },
    // 当前页码发生改变的时候触发函数
    handleCurrentChange (newPage) {
      this.userInfo.pagenum = newPage;
      this.getUserList(); // 看到p50
    },
    // 当添加对话框结束时调用此函数
    addDialogClosed () {
      this.$refs.addFormRef.resetFields(); //清空输入框中的内容
    },
    // 当修改用户对话框结束时调用此函数
    editDialogClosed () {
      this.$refs.editFormRef.resetFields(); //清空输入框中的内容
    },
    // 添加用户按钮
    addUser () {
      // 表单数据校验
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        //发送网络请求后台接口
        const { data: res } = await this.$ajax.post("/users", this.addForm);
        if (res.meta.status !== 201) {
          this.$message.error("请求出错");
        }
        this.$message.success("添加成功");

        //隐藏添加用户的对话框
        this.addDialogVisible = false;
        // 重新获取用户列表数据
        this.getUserList();
      });
    },
    // 编辑用户信息按钮
    async showEditDialog (id) {
      const { data: res } = await this.$ajax.get("/users/" + id);
      this.editForm = res.data;
      this.editDialogVisible = true;
    },
    // 提交修改的用户信息
    async editUserInfo () {
      this.$refs.editFormRef.validate(valid => {
        if (valid) return;
      });
      // 发起修改用户请求
      const { data: res } = await this.$ajax.put(
        "/users/" + this.editForm.id,
        this.editForm
      );

      if (res.meta.status !== 200) {
        return this.$message.error("修改信息错误");
      }

      //隐藏添加用户的对话框
      this.editDialogVisible = false;
      // 重新获取用户列表数据
      this.getUserList();
      this.$message.success("修改用户信息成功");
    },
    // 根据用户id删除对应信息
    async deleteUserById (id) {
      const resConfirm = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => {
        return err;
      });

      if (resConfirm !== "confirm") {
        return this.$message.info("您已取消删除");
      } else {
        const { data: res } = await this.$ajax.delete("/users/" + id);
        if (res.meta.status !== 200) {
          return this.$message.error("请求错误");
        }
        this.$message.success("删除成功");
      }

      // 重新获取用户列表数据
      this.getUserList();
    },
    async setRole (user) {
      this.user = user;

      // 在展示对话框之前，拿到所有的用户权限列表
      const { data: res } = await this.$ajax.get("/roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限列表失败");
      }
      this.roleList = res.data;
      this.setRoleDialogVisible = true;
    },
    // 保存角色更改按钮
    async saveRoleInfo () {
      if (!this.selectedRoleId) {
        return this.$message.error("请选择角色");
      }

      const { data: res } = await this.$ajax.put(
        `/users/${this.user.id}/role`,
        {
          rid: this.selectedRoleId
        }
      );

      if (res.meta.status !== 200) {
        return this.$message.error("角色更改失败");
      }
      this.$message.success("角色更改成功");
      this.getUserList();
      this.setRoleDialogVisible = false;
    },
    // 当分配角色对话框关闭时调用
    setRoleDialogClosed () {
      this.selectedRoleId = "";
      this.user = {}; 
    }
  },

  created () {
    this.getUserList();
  }
};
</script>

<style lang="less" scoped>
.el-input {
  margin-bottom: 20px;
}
</style>
